package com.xxg.renrensearch.dao;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;

import static org.springframework.data.mongodb.core.query.Criteria.where;


/**
 * 图片已失效Dao
 *
 * @author xuxiaogang
 * @date 2021-12-16
 */
@Repository
public class ImageNotFoundDao {
    private final MongoTemplate mongoTemplate;

    public ImageNotFoundDao(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
        createCollection();
    }

    /**
     * 创建collection
     */
    private void createCollection() {
        String collectionName = "imageNotFound";
        MongoCollection<Document> collection;
        if (!mongoTemplate.getCollectionNames().contains(collectionName)) {
            collection = mongoTemplate.createCollection(ImageNotFound.class);
            createIndex(collection);
        }
    }

    /**
     * 创建索引
     *
     * @param collection 数据集
     */
    private void createIndex(MongoCollection<Document> collection) {
        collection.createIndex(Indexes.ascending("fileName"));
    }

    /**
     * 插入失效图片记录
     *
     * @param imageNotFound 图片信息
     */
    public void insert(ImageNotFound imageNotFound) {
        imageNotFound.setId(null);
        imageNotFound.setCreateTime(new Date());
        mongoTemplate.save(imageNotFound);
    }

    /**
     * 查询图片是否存在
     *
     * @param fileName 图片名称
     * @return true-存在，false-不存在
     */
    public boolean exists(String fileName) {
        Query query = new Query(where("fileName").is(fileName));
        return mongoTemplate.exists(query, ImageNotFound.class);
    }
}
